import {
  ArrowRightOutlined,
  EnvironmentOutlined,
  FlagOutlined,
} from '@ant-design/icons';
import { Button, Flex, FloatButton, Popover, Tooltip } from 'antd';
import type { LngLat } from 'mapbox-gl';
import React, { useEffect, useState } from 'react';
import CoordinateTrans, {
  CoordinateInput,
} from '@/components/MapView/components/CoordinateTrans';
import FormatChange from '@/components/MapView/components/CoordinateTrans/FormatChange';
import { Format } from '@/components/MapView/components/CoordinateTrans/weapon';
import type Mapless from '@/components/MapView/Mapless';
import { attachMarker, getMarker } from '@/components/MapView/Mapless';
import styles from '../index.module.less';

const XDMode: React.FC<{
  mapless: Mapless | undefined;
  lnglat?: LngLat;
}> = (props) => {
  const { mapless, lnglat } = props;

  const [lng, setLng] = useState<number | null>(113.27);
  const [lat, setLat] = useState<number | null>(23.13);

  useEffect(() => {
    if (mapless) {
      attachMarker(mapless, 'lnglatTool-marker');
    }
  }, [mapless]);

  useEffect(() => {
    if (lnglat) {
      setLng(lnglat.lng);
      setLat(lnglat.lat);
    }
  }, [lnglat]);

  // useEffect(() => {
  //   if (lng !== null && lat !== null) {
  //     mapless?.flyTo({
  //       center: [lng, lat]
  //     });
  //   }
  // }, [lng, lat, mapless]);

  const [showMarker, setShowMarker] = useState(false);

  const setMarker = (lng: number, lat: number) => {
    const mm = getMarker(mapless, 'lnglatTool-marker');
    mm?.removeMarker('test');
    if (showMarker) {
      mm?.addMarker('test', [lng, lat], {
        icon: 'locating',
        popup: `
          <div style="margin: 5px 10px;user-select: text;">
            <div>经度：${lng}</div>
            <div>纬度：${lat}</div>
          </div>
        `,
      });
    }
  };

  useEffect(() => {
    if (showMarker) {
      if (lng !== null && lat !== null) {
        setMarker(lng, lat);
      }
    }
  }, [showMarker, lng, lat]);

  const [format, setFormat] = useState(Format.DDD);

  return (
    <Popover
      placement="right"
      title={
        <Flex gap={8} align="center">
          <Flex gap={8} align="center" flex={1}>
            输入坐标信息:
            <FormatChange showFormat={format} onFormatChange={setFormat} />
          </Flex>
          <Tooltip title={showMarker ? '隐藏标记' : '显示标记'}>
            <Button
              type="text"
              size="small"
              onClick={() => {
                const next = !showMarker;
                setShowMarker(next);
                const mm = getMarker(mapless, 'lnglatTool-marker');
                if (!next) {
                  mm?.removeMarker('test');
                } else {
                  if (lng !== null && lat !== null) {
                    mapless?.flyTo({
                      center: [lng, lat],
                    });
                    setMarker(lng, lat);
                  }
                }
              }}
            >
              <FlagOutlined
                style={
                  showMarker ? { color: 'var(--theme-color-primary)' } : {}
                }
              />
            </Button>
          </Tooltip>
          <Tooltip title="定位到当前位置">
            <Button
              type="text"
              size="small"
              onClick={() => {
                if (lng !== null && lat !== null) {
                  mapless?.flyTo({
                    center: [lng, lat],
                  });
                  setMarker(lng, lat);
                }
              }}
            >
              <ArrowRightOutlined />
            </Button>
          </Tooltip>
        </Flex>
      }
      content={
        <Flex vertical gap={4}>
          {format === Format.STAR ? (
            <CoordinateInput
              value={`${lng?.toFixed(6)} ${lat?.toFixed(6)}`}
              onChange={(val) => {
                if (val) {
                  const [lng, lat] = val;
                  setLng(Number(lng));
                  setLat(Number(lat));
                }
              }}
            />
          ) : (
            <>
              <CoordinateTrans
                showFormat={format}
                maximum={180}
                minimum={-180}
                units={['W', 'E']}
                value={lng}
                onChange={(val) => {
                  setLng(val);
                }}
              />
              <CoordinateTrans
                showFormat={format}
                maximum={90}
                minimum={-90}
                value={lat}
                units={['S', 'N']}
                onChange={(val) => {
                  setLat(val);
                }}
              />
            </>
          )}
        </Flex>
      }
      trigger="click"
    >
      <FloatButton
        className={styles.xdbtn}
        style={{ zIndex: 1000 }}
        icon={<EnvironmentOutlined />}
        shape="square"
        tooltip={{
          title: '坐标定位',
          placement: 'left',
          rootClassName: styles.tooltip,
        }}
      />
    </Popover>
  );
};

export default React.memo(XDMode);
